import { useEffect, useRef } from "react";

const defaultOptions: MutationObserverInit = {
  subtree: true,
  childList: true,
  attributeFilter: ["style", "class"],
};

const useMutateObserver = (
  nodeOrList: HTMLElement | HTMLElement[],
  callback: MutationCallback,
  options: MutationObserverInit = defaultOptions
) => {
  useEffect(() => {
    if (!nodeOrList) {
      return;
    }

    let instance: MutationObserver;

    const nodeList = Array.isArray(nodeOrList) ? nodeOrList : [nodeOrList];

    if ("MutationObserver" in window) {
      instance = new MutationObserver(callback);
      nodeList.forEach((element) => {
        instance.observe(element, options);
      });
    }
    /**
     * 支持单个节点，多个节点的 observe。
     * 默认的 options 是 { attributes: true, childList: true, subtree: true }
     * 在销毁的时候，调用 takeRecords 删掉所有剩余通知，调用 disconnect 停止接收新的通知：
     */
    return () => {
      instance?.takeRecords();
      instance?.disconnect();
    };
  }, [nodeOrList, options]);
};

export default useMutateObserver;
